package com.wms.system.service.impl.wcs;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms.common.config.RuoYiConfig;
import com.wms.common.exception.ServiceException;
import com.wms.system.domain.wcs.PackingExcelTemplate;
import com.wms.system.domain.wcs.PackingList;
import com.wms.system.domain.wcs.PackingListSon;
import com.wms.system.mapper.wcs.PackingExcelTemplateMapper;
import com.wms.system.mapper.wcs.PackingListMapper;
import com.wms.system.mapper.wcs.PackingListSonMapper;
import com.wms.system.service.wcs.IPackingListService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PackingListServiceImpl implements IPackingListService {
    @Autowired
    private PackingListMapper packingListMapper;

    @Autowired
    private PackingListSonMapper packingListSonMapper;

    @Autowired
    private PackingExcelTemplateMapper packingExcelTemplateMapper;

    @Override
    public List<PackingList> queryList(PackingList packingList) {
        List<PackingList> dataList = packingListMapper.selectList(new LambdaQueryWrapper<PackingList>()
                .eq(packingList.getStatus() != null, PackingList::getStatus, packingList.getStatus())
                .in(!CollectionUtils.isEmpty(packingList.getStatusList()), PackingList::getStatus, packingList.getStatusList())
                .like(StringUtils.isNotBlank(packingList.getCustomeName()), PackingList::getCustomeName, packingList.getCustomeName())
                .like(StringUtils.isNotBlank(packingList.getProjectCode()), PackingList::getProjectCode, packingList.getProjectCode())
                .like(StringUtils.isNotBlank(packingList.getOrderCode()), PackingList::getOrderCode, packingList.getOrderCode())
                .ge(packingList.getDeliveryDateStart() != null, PackingList::getDeliveryDate, packingList.getDeliveryDateStart())
                .le(packingList.getDeliveryDateEnd() != null, PackingList::getDeliveryDate, packingList.getDeliveryDateEnd())
                .ge(packingList.getPackingDateStart() != null, PackingList::getPackingDate, packingList.getPackingDateStart())
                .le(packingList.getPackingDateEnd() != null, PackingList::getPackingDate, packingList.getPackingDateEnd())
                .orderByDesc(PackingList::getCreatedTime)
        );
        //判断是否有缺料
        if(!CollectionUtils.isEmpty(dataList)) {
            Set<String> set = packingListSonMapper.selectList(new LambdaQueryWrapper<PackingListSon>()
                    .in(PackingListSon::getOrderCode, dataList.stream().map(PackingList::getOrderCode).toList())
                    .apply("shipped_number > stock_qty")
            ).stream().map(PackingListSon::getOrderCode).collect(Collectors.toSet());
            dataList.forEach(x -> x.setIsMissingParts(set.contains(x.getOrderCode())?0:1));
        }
        return dataList;
    }


    @Override
    public void exportExcel(HttpServletResponse response, PackingList packingList){
        PackingExcelTemplate packingExcelTemplate = packingExcelTemplateMapper.selectById(packingList.getPackingExcelTemplateId());
        PackingList order = packingListMapper.selectById(packingList.getId());
        List<PackingListSon> sonList = packingListSonMapper.selectList(new LambdaQueryWrapper<PackingListSon>()
                .eq(PackingListSon::getOrderCode,order.getOrderCode()));
        sonList.sort(Comparator.comparing(x->Integer.parseInt(x.getSerialNumber())));

        String absoluteFilePath = RuoYiConfig.getProfile()+packingExcelTemplate.getTemplatePath();
        InputStream template ;
        try {
            template = new FileInputStream(absoluteFilePath);
        }catch (Exception e){
            throw new ServiceException("读取EXCEL模板文件异常");
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + packingExcelTemplate.getTemplateName() + ".xlsx\"");

        try (ExcelWriter writer = EasyExcel.write(response.getOutputStream())
                     .withTemplate(template)
                     .build()) {
            FillConfig fillConfig = FillConfig.builder()
                    .forceNewRow(Boolean.TRUE) // 强制每个元素创建新行
                    .build();

            WriteSheet sheet = EasyExcel.writerSheet().build();

            // 填充动态列表
            writer.fill(new FillWrapper("o", Arrays.asList(order)), fillConfig, sheet);
            writer.fill(new FillWrapper("os", sonList), fillConfig, sheet);

            writer.finish();
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("EXCEL文件导出失败");
        }

    }
}
